package com.atguigu.yygh.user.service.impl;


import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.security.PermitAll;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl  extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private PatientService patientService;


    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());

        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        baseMapper.updateById(userInfo);
    }

    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVO获取手机号  验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();


        //判断是否为空
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }


        //todo 判断验证码是否一致
        String mobleCode=redisTemplate.opsForValue().get(phone).toString();
        System.out.println("test");
            if(!code.equals(mobleCode)){
                throw  new YyghException(ResultCodeEnum.CODE_ERROR);
            }else {

                //绑定手机号码
                UserInfo userInfo = null;
                if(!StringUtils.isEmpty(loginVo.getOpenid())) {
                    userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
                    if(null != userInfo) {
                        userInfo.setPhone(loginVo.getPhone());
                        this.updateById(userInfo);
                    } else {
                        throw new YyghException(ResultCodeEnum.DATA_ERROR);
                    }
                }

                //如果为空做正常的手机登录
                if(userInfo ==null){

                    //判断是否是第一次登录  （根据手机号查询数据库比对）
                    QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

                    wrapper.eq("phone", phone);

                    userInfo = baseMapper.selectOne(wrapper);
                    if (userInfo == null) {
                        userInfo = new UserInfo();
                        userInfo.setName("");
                        userInfo.setPhone(phone);
                        userInfo.setStatus(1);
                        baseMapper.insert(userInfo);
                    }

                }


                if (userInfo.getStatus() == 0) {
                    throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
                }

                //校验用户状态


                //不是第一次直接登陆


                //返回信息（用户名  token）
                //返回页面显示名称
                Map<String, Object> map = new HashMap<>();
                String name = userInfo.getName();
                if (StringUtils.isEmpty(name)) {
                    name = userInfo.getNickName();
                }
                if (StringUtils.isEmpty(name)) {
                    name = userInfo.getPhone();
                }
                map.put("name", name);

                // JWT生成
                String token = JwtHelper.createToken(userInfo.getId(), name);

                map.put("token", token);
                redisTemplate.delete(phone);
                return map;


            }

    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);

        UserInfo userInfo = baseMapper.selectOne(queryWrapper);


        return userInfo;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue()==0 || status.intValue()==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }
    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map=new HashMap<>();

        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    //审批功能
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus==2 || authStatus==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }

    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        String name = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        //对条件判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }

        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);

        userInfoPage.getRecords().stream().forEach(item->{
             this.packageUserInfo(item);
        });


        return userInfoPage;
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;


    }
}
